import type { LanguageType } from '@lingshu/language-lib';
import { getBatchLangModuleData } from '@lingshu/language-lib';
import { createI18n } from 'vue-i18n';
import { waringTip } from '@/utils/WaringTips.ts';
import { getLangJson } from './model/index.ts';
import { proxyLanguageRequest } from './TransformRequest.ts';

const LANG_MODULE = '';

const i18n = createI18n({
  locale: '',
  legacy: false,
  messages: {},
});

export async function changeLang(config: {
  lang: LanguageType
  langJson?: Record<string, any>
}) {
  const { lang } = config;

  let appLangJson = getLangJson();

  try {
    const data = await getBatchLangModuleData([{
      moduleCode: LANG_MODULE,
      langJson: appLangJson,
    }], proxyLanguageRequest);
    appLangJson = data.langMap[LANG_MODULE] || {};
  } catch (error) {
    waringTip(error);
    console.error(error);
  }

  i18n.global.locale.value = lang;
  i18n.global.setLocaleMessage(lang, appLangJson);

  return Promise.resolve(true);
}
export const t = i18n.global.t;

export default i18n;
